package com.surekam.mnai.webservice.server;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.annotation.PostConstruct;
import javax.ws.rs.Encoded;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.sun.jersey.api.core.ResourceContext;
import com.surekam.mnai.util.coder.HMacMD5JM;
import com.surekam.mnai.webservice.WsConstants;

@Component
@Path("/auth")
public class AuthUserService {
	private static Logger logger = LoggerFactory.getLogger(AuthUserService.class.getName());

	private static final String CHARSET = ";charset=UTF-8";

	@Context
	protected ResourceContext resource;

	@PostConstruct
	public void init() {
		logger.info("Authentication User WebService Init......");		
	}

	@GET
	@Path("authuser/{imeiCode}")
	@Produces({ MediaType.TEXT_PLAIN + CHARSET })
	@Encoded
	public String authUser(@PathParam("imeiCode") String imeiCode) {
		logger.debug("进入方法AuthUser");
		String hmacMd5 = null;
		try {
			hmacMd5 = HMacMD5JM.hmacMd5(imeiDecode(imeiCode));

		} catch (NoSuchAlgorithmException e) {
			logger.info("登陆失败");
			return WsConstants.FAILURE;
		} catch (InvalidKeyException e) {
			logger.info("登陆失败");
			return WsConstants.FAILURE;
		}
		logger.info("登陆成功");

		return hmacMd5;
	}

	private static String imeiDecode(String str) {
		String decode = null;
		try {
			decode = URLDecoder.decode(str, WsConstants.CHARSET);
		} catch (UnsupportedEncodingException e) {
			logger.error("String Decode error!!!", e);
			return null;
		}
		return decode;
	}
}
